# 感知机
#
#
origin = "限时优惠！免费中奖，点击链接领取 iPhone：https://x.xx/abc 退订回TD"
globalList = ["免费", "中奖", "点击", "链接", "退订", "优惠"]  # 字典


# {
#  "feature_schema": ["免费","中奖","点击","链接","退订","优惠"],
#  "weights": [0.0, 0.0, 0.1, 0.1, 0.1, 0.0],
#  "bias": 0.1,
#  "label_mapping": { "positive": "垃圾", "negative": "正常" },
#  "preprocess": { "feature_type": "binary", "lowercase": true }
# }


class Perceptron:
    def __init__(self, maxRound, feature, weights, bias, learningRate, label):
        self.maxRound = maxRound
        self.feature = feature
        self.weights = weights
        self.bias = bias
        self.learningRate = learningRate
        self.label = label
        return

    def fit(self, round):
        round = round + 1
        self.round = round
        if round > self.maxRound:
            print(self.weights)
            return 0

        pred = self.sign()
        if pred == self.label:
            # 这里判对了。那么程序应该结束了。
            print(self.weights)
            return
        else:
            # 这里判错了 标签判断是否是加分还是减分
            if not self.label:
                rate = -self.learningRate
            else:
                rate = self.learningRate

            for i in range(len(self.weights)):
                if self.feature[i] > 0:
                    self.weights[i] += rate

            self.bias = self.bias + rate
            self.fit(round)

    def sign(self):
        score = 0
        for i in range(len(self.weights)):
            score += self.feature[i] * self.weights[i]
        score += self.bias
        return score > 0


# 点击链接退订领取奖励 点击, 链接, 退订
per = Perceptron(10, [0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], 0, 0.1, True)
per.fit(0)
